<?php namespace Reezy\APICrypt;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function config;


class APICryptMiddleware implements MiddlewareInterface
{
    /**
     * @var APICrypt
     */
    private $crypt;

    public function __construct(StreamFactoryInterface $streamFactory)
    {
        $this->crypt = new APICrypt(config('api_crypt') ?? [], $streamFactory);
    }

    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @throws APICryptException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        [$newRequest, $aesKey, $aesIv] = $this->crypt->decrypt($request);

        $response = $handler->handle($newRequest);

        return  $this->crypt->encrypt($response, $aesKey, $aesIv);
    }
}
